package LeetCode.stack_queue;

import java.util.LinkedList;
import java.util.Queue;
public class LC_225 {
    private Queue<Integer> queue1;
    private Queue<Integer> queue2;
    Queue<Integer> temp1;
    Queue<Integer> temp2;
    public LC_225() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if(!queue1.isEmpty()){
            queue1.offer(x);
            return;
        }
        queue2.offer(x);
    }

    public int pop() {
        if(empty()){
            return -1; // 两个队列都为空
        }
//        if(!queue1.isEmpty()){
//            int size = queue1.size();
//            int val = -1;
//            for (int i = 0; i < size - 1; i++) {
//                val = queue1.poll();
//                queue2.offer(val);
//            }
//            return queue1.poll();
//        } else {
//            int size = queue2.size();
//            int val = -1;
//            for (int i = 0; i < size - 1; i++) {
//                val = queue2.poll();
//                queue1.offer(val);
//            }
//            return queue2.poll();
//        }
        temp1 = (queue1.isEmpty() ? queue1 : queue2); // temp1为空的
        temp2 = (temp1 == queue1 ? queue2 : queue1); // temp2为非空
        int size = temp2.size(); // 因为temp2.size()是变化的, 所以不能这样写
        //for (int i = 0; i < temp2.size()- 1; i++){
        for (int i = 0; i < size- 1; i++){
            int val = temp2.poll();
            temp1.offer(val);
        }
        return temp2.poll();

    }

    public int top() {
        if(empty()){
            return -1;
        }
        if(!queue1.isEmpty()){
            int size = queue1.size();
            int val = -1;
            for (int i = 0; i < size; i++) {
                val = queue1.poll();
                queue2.offer(val);
            }
            return val;
        } else {
            int size = queue2.size();
            int val = -1;
            for (int i = 0; i < size; i++) {
                val = queue2.poll();
                queue1.offer(val);
            }
            return val;
        }
    }
    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }

    public static void main(String[] args) {
        LC_225 LC225 = new LC_225();
        LC225.push(5);
        LC225.push(6);
        LC225.push(7);
        LC225.push(8);
        int x = LC225.pop();
        int y = LC225.pop();
        System.out.println(x + " " + y);
        System.out.println(LC225.top());
    }
}
